var zTreeObj;
var currentNode;
var trees = new Array();
var myTrees = new Array();
$(function() {
	$("button.securBtn").bind("click",function(){
		var id = this.id;
		switch(id){
		case "save":saveAction();break;
		case "list":goListAction();break;
		case "ofusers":goUserAction();break;
		default:;
		}
		
	}).button();
	$("#applySec").bind("click",function(){
		var postdata="bean.name="+$("#name").val();
		doPost("admin/securole/secu-role!apply",postdata,function(){
			alert("权限审核通过");
		});
	});
	//alert(action);
	if(action=='update'){
	$.ajax({
		async:false,
		url: "admin/treenode/tree-node!allbyacegi",
		dataType: 'json',
		data: "secRole.name="+secRole,
		success: function(d,ts,jq){
			myTrees = d;		
		}

	});
	}
	var setting = {
			check:{
				enable:true
			},
			async : {
				enable : true,
				url : "admin/treenode/tree-node!listall",
				autoParam : ["id=bean.id"],
				otherParam:{}
            },
			callback:{
				onExpand: zTreeOnExpand,
				onAsyncSuccess:zTreeOnAsyncSuccess
			}
 };
 var root = {
	  	  name : "系统全部权限",
			  open : true,
			  nocheck:false,
			  id:"root",
			  isParent:true
  } ;
  var zNodes = [
	     root                      
      ];
 zTreeObj = $.fn.zTree.init($("#resTree"), setting,zNodes);
 var nodes = zTreeObj.getNodes();
 zTreeObj.expandNode(nodes[0],true,false,true,true);	
 
	$.getJSON("loginpage/login-page!gets",function(datas){
		var urls = $("#msgPannel select");
		for(var i=0;i<datas.length;i++){
			var url = $("<option></option>");
			url.val(datas[i].targetUrl).text(datas[i].targetUrl);
			if(turl==datas[i].targetUrl){
				url.attr("selected",true);
			}
			urls.append(url);
		}
		
	});
	
});
function zTreeOnExpand(event, treeId, treeNode){
	var nodes = treeNode.children;
	for(var i=0;i<nodes.length;i++){
		var nd = nodes[i];
		if($.inArray(nd.id,myTrees)!=-1){
			zTreeObj.checkNode(nd, true, true);

		}		
	}

}
function zTreeOnAsyncSuccess(event, treeId, treeNode, msg){
	var nodes = treeNode.children;
	
	for(var i=0;i<nodes.length;i++){
		if($.inArray(nodes[i].id,myTrees)!=-1){
			zTreeObj.checkNode(nodes[i], true, true);

		}	
		zTreeObj.expandNode(nodes[i],true,false,true,true);	
	}

}

function saveAction() {
	var postdata = '';
	var i=0;
	
	var nodes = zTreeObj.getCheckedNodes(true);

	$.each(nodes,function(jdx,nd){
		if(nd.id=="root")return;
		postdata += '&bean.treeNode[' + (i++) + '].id=' + nd.id;
	});
	postdata+="&bean.name="+$("#name").val();
	var loginurl = $("#msgPannel select").val();
	if(loginurl=="" || loginurl==undefined){
		loginurl="apps";
	}
	postdata+="&bean.login.targetUrl="+loginurl;
	postdata+="&bean.priority="+priority;
	postdata+="&bean.description="+ $("#description").val();
	//alert(postdata);
	var url = "admin/securole/secu-role!"+action;
	doSubmit(url,postdata,function(){
		createNotify("权限保存成功");		
	});
	
}

function goListAction() {
	doAjaxLink("admin/securole/start");
}
function goUserAction(){
	doAjaxLink('admin/securole/useroflist?acegiName='+secRole);
}